package com.zzh.mvvm.factory;


import android.app.Application;

import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

/**
 * Created by zzh on 2023/11/13.
 *
 * @date: 2023/11/13 14:36
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.mvvm.factory
 * <p>
 * 重写此类，可以获取多个DSModel（数据源实例）
 * 覆写BaseRabbitActivity#createViewModel(FragmentActivity, Class<T>)
 * 和
 * BaseRabbitFragment#createViewModel(FragmentActivity, Class<T>)
 * 使用HRabbitFactory类进行注入。create方法区分ViewModel
 */
public class HRabbitFactory extends ViewModelProvider.AndroidViewModelFactory {

    Application application;

    private static HRabbitFactory factory;


    public HRabbitFactory(Application application) {
        super(application);
        this.application = application;
    }

    public static HRabbitFactory getSubInstance(Application app) {
        if (factory == null) {
            synchronized (HRabbitFactory.class) {
                if (factory == null) {
                    return factory = new HRabbitFactory(app);
                }

            }
        }
        return factory;
    }

    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        if (mOnCreateViewModelListener != null) {
            T subModelClass = mOnCreateViewModelListener.create(this, application, modelClass);
            if (subModelClass == null) {
                return super.create(modelClass);
            } else {
                return subModelClass;
            }
        } else {
            return super.create(modelClass);
        }
    }

    private static OnCreateViewModelListener mOnCreateViewModelListener;

    public static void registerCreateViewModelListener(OnCreateViewModelListener onCreateViewModelListener) {
        mOnCreateViewModelListener = onCreateViewModelListener;
    }

    public interface OnCreateViewModelListener {
        <T extends ViewModel> T create(ViewModelProvider.AndroidViewModelFactory factory, Application app, Class<T> modelClass);
    }
}
